package SecondeStage.Networkprogramming.TcpFileUpload;

import SecondeStage.Networkprogramming.StreamUtils;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpFileUploadServer {
    public static void main(String[] args) throws Exception {
        // 1. 服务端在本机监听8888
        ServerSocket serverSocket =new ServerSocket(8888);
        System.out.println("服务端在8888端口监听.......");
        // 2. 等待连接
        Socket socket=serverSocket.accept();
        // 3. 读取客户端发送的数据，通过socket获取输入流
        BufferedInputStream bufferedInputStream =new BufferedInputStream(socket.getInputStream());
        byte[] bytes = StreamUtils.streamToByteArray(bufferedInputStream);
        // 4. 将得到的bytes数组，写入到指定的路径
        String filePath = "D:\\Java\\JavaProject\\test\\2.jpg";
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(filePath));
        bufferedOutputStream.write(bytes);
        // 5. 向客户端回复收到图片
        // 通过socket获取输出流(字符)
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bufferedWriter.write("收到图片");
        bufferedWriter.flush(); // 把内容刷新到数据通道
        socket.shutdownOutput(); // 设置写入结束标记
        // 6.把不需要再使用的输入流关闭和资源
        bufferedInputStream.close();
        bufferedOutputStream.close();
        bufferedWriter.close();
        socket.close();
        serverSocket.close();
    }
}
